package com.yujie.service.imp;

import com.yujie.dao.MenuDao;
import com.yujie.dao.SysUserDao;
import com.yujie.model.Menu;
import com.yujie.model.SysUser;
import com.yujie.model.dto.SysRoleDTO;
import com.yujie.model.dto.SysUserDTO;
import com.yujie.model.vo.SysUserVO;
import com.yujie.security.LoginUser;
import com.yujie.service.SysUserService;
import com.yujie.utils.WebExceptionUtil;
import com.yujie.utils.JwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired(required = false)
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public SysUserDTO getSysUserAndRoleAndMenuByUserName(String username) {
        SysUserDTO sysUserDTO = sysUserDao.getSysUserAndRoleByUserName(username);
        if (sysUserDTO == null){
            return null;
        }
        List<SysRoleDTO> roles = sysUserDTO.getRoles();
        for (SysRoleDTO role : roles) {
            List<Menu> menuList = menuDao.listMenuByRoleId(role.getId());
            role.setMenuList(menuList);
        }
        return sysUserDTO;
    }

    @Override
    public SysUserVO getLoginUser(String username, String password) throws Exception{
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        //验证用户密码是否正确
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //获取登录用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId=loginUser.getSysUser().getId().toString();
        //创建token,永不过期
        String token = JwtUtil.createJWT(userId,7970272710000L);
        loginUser.setNewToken(token);
        //把用户必要的信息放入到SysUserVO
        SysUserVO sysUserVO = new SysUserVO();
        sysUserVO.setToken(token);
        BeanUtils.copyProperties(loginUser.getSysUser(),sysUserVO);
        //设置1天的过期时间
        redisTemplate.opsForValue().set("loginUser:"+userId,loginUser, 60*60*24,TimeUnit.SECONDS);
        return sysUserVO;
    }

    @Override
    public void saveSysUser(SysUser sysUser) throws Exception {
         sysUserDao.insert(sysUser);
    }
}
